/**
 * Looker  新闻整合系统
 * Author  :solosky <solosky772@qq.com>
 * File    :Data.js
 * Date    :August 16, 2009
 * License : Apache License 2.0 
 */

/**
 *  新闻包
 *  这个包提供的新闻列表的生成和新闻正文的显示
 */
 
/**
 * 新闻列表类
 * 获取新闻并在NewsListWidget上显示
 */
 
 var NewsList = function(widget){
	//配置信息
	this.options = {
		category : widget.getConfig("category"),	//显示栏目
		limit    : widget.getConfig("newscnt"),	//显示条数
		showType : widget.getConfig("showtype"), //显示方式，list,blog,image
		accordion: widget.getConfig("accordion")	//是否启用折叠
	};
	//翻页配置
	this.navSettings = {
		items_per_page:this.options.limit,
		num_display_entries:7,
		current_page:0,
		num_edge_entries:1,
		link_to:"#",
		prev_text:"上页",
		next_text:"下页",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		listHander:this,
		callback:function(page,jq){this.listHander.load(page+1);return true;}
	};
	// 翻页对象
	this.pagination = null;
	//当前页码
	this.curpage    = 0;
	//当前下载的新闻列表数据
	this.curdata    = null;  
	//所属widget
	this.widget     = widget;
	//总共的记录数
	this.total      = -1;  
	//地址
	this.url        = Config.URL.NewsList; 
	
	
	/////////////////////////////////////////////////////////////////////////////////////
	//生成url
	this.getURL = function(page){
		var url = this.url;
		url = url.replace("{category}", this.options.category);
		url = url.replace("{total}", this.total);
		url = url.replace("{page}", page);
		url = url.replace("{limit}", this.options.limit);
		return url;
	};
	//加载新闻数据
	this.load = function(page){
		//alert("load"+page);
		widget.overlay(true);
		var self = this;
		var suc = function(data){
			if(data.total<1){
				self.widget.setContent("对不起，暂时还没有新闻，请换个栏目试试。");	
				return;
			}
			self.total = data.total;
			self.curdata = data.data;
			self.curpage = page;
			self.render();
			self.bind();
			widget.overlay(false);
		};
		var err = function(data){
			widget.setContent("载入失败，请重试");
		};
		var request = new ServerRequest({
				url      : this.getURL(page),
				dataType : "json",
				success : suc,
				error    : err
			});
		RequestManager.addRequest(request);
	};
	//绑定事件
	this.bind = function(){
		var w = this.widget.$widget;
		var s = this.options;
		var self = this;
		if( (s.showType=="blog" || s.showType=="image") && s.accordion=="true" ){
			w.find(".list-content").LiteAccordion({header:".accordion-title",animated:"slide"});
		}else{
		}
		w.find("a img").parent().lightBox();
		
		//查看正文事件
		if(s.showType=="blog" || s.showType=="image"){
				w.find("a.news-detail").each(function(i){
					this.onclick = function(){
							NewsView.open(self.curdata[i].newshash);
                            return false;
						};	
				});	
		}else{
			w.find(".list-news-list-entry a").each(function(i){
				this.onclick = function(){
					NewsView.open(self.curdata[i].newshash);	
                    return false;
				};
			});			
		}
	};
	//输出新闻列表
	this.render = function(){
		var s = this.options;
		var $list = NewsTemplate.List.renders[s.showType](this.curdata);
		var $lc = this.widget.$widget.find(".list-content").html($list);

		if(!this.pagination){
			this.pagination = this.widget.$widget.find(".list-nav").pagination(this.total, this.navSettings);	
		}
	};
	//输出widget正文
	this.show  = function(){
		this.load(1);
	};	 
 };
 
 /**
  * 新闻模版
  */
  var NewsTemplate = {
	  List : {
		entry:{
			list : ' <div class="list-news-list-entry"><a href="#" title="{fulltitle}" onclick="Newhelper.openView(\'newshash\')">{subtitle}</a><span>{goodtime}</span></div>',
			blog : '<div class="list-news-blog-entry">'+
            		'	<div class="list-news-blog-title  accordion-title"><a href="#" title="{fulltitle}">{subtitle}</a><span>{goodtime}</span></div>'+
            		'	<div class="accordion-content">'+
              		'		<div class="list-news-blog-image"> {thumb}</div>'+
              		'		<div class="list-news-blog-intro"> {intro}.&gt;&gt;<a href="#" class="news-detail">全文</a></div>'+
              		'		<div class="list-news-blog-info"> [{cleartime}|<span class="icon-comment">推荐({dig})</span>|<span class="icon-view">查看({view})</span>|<span class="icon-attach">附件({attach})</span>|<span class="icon-image">图片({image})</span>] </div>'+
            		'	</div>'+
          			'</div>',
			image : ' <div class="list-news-image-entry">'+
          			' <div class="list-news-image-title accordion-title"> <a href="#" title="{fulltitle}">{subtitle}</a><span>{goodtime}</span> </div>'+
            		'<div class="list-news-image-info">'+
             		' 	<div class="list-news-image-image">{thumb}</div>'+
            		' 	<div class="list-news-image-intro"> {intro}.&gt;&gt;<a href="#" class="news-detail">全文</a></div>'+
              		'  	<div class="clear"></div>'+
           			'</div>'+
          			'</div>'
		},
		////////////////////////////////////////////
		//渲染新闻列表新闻函数
		renders :{
			list : function(data){
				var b = new Util.Str.Builder();
				var date = new Date();
				for(var i=0; i<data.length; i++){
					var t = NewsTemplate.List.entry.list;
					var d = data[i];
					t = t.replace("{fulltitle}", d.title);
					t = t.replace("{subtitle}", NewsHelper.format.subTitle(d.title,20));
					t = t.replace("{goodtime}", NewsHelper.format.goodTime(d.date));		
					t = t.replace("{newshash}", d.newshash);		
					
					b.append(t);
				}
				return b.toString();
			},
			blog : function(data){
				var b = new Util.Str.Builder();
				for(var i=0; i<data.length; i++){
					var t = NewsTemplate.List.entry.blog;
					var d = data[i];
					t = t.replace("{newshash}", d.newshash);
					t = t.replace("{fulltitle}", d.title);
					t = t.replace("{subtitle}", NewsHelper.format.subTitle(d.title,20));
					t = t.replace("{intro}", NewsHelper.format.subIntro(d.intro,d.thumb.length>0 ? 120 :200));
					t = t.replace("{cleartime}", NewsHelper.format.clearTime(d.date));
					t = t.replace("{goodtime}", NewsHelper.format.goodTime(d.date));
					t = t.replace("{dig}", d.dig);
					t = t.replace("{view}", d.view);
					t = t.replace("{image}", d.image);
					t = t.replace("{attach}", d.media-d.image);
					var imgs = new Util.Str.Builder();
					if(d.thumb.length>0){
						var thumbs = d.thumb.split("|");
						for(var j=0; j<thumbs.length &&j<3;j++){
							imgs.append('<a href="'+NewsHelper.format.imageURL(thumbs[j],"full")+'" title="'+d.title+'">');
							imgs.append('<img src="'+NewsHelper.format.imageURL(thumbs[j],"small")+'" alt="'+d.title+'"/></a>');	
						}
					}
					 t = t.replace("{thumb}",imgs.toString());
					b.append(t);
					}
					return b.toString();			
			},
			image : function(data){
				var b = new Util.Str.Builder();
				for(var i=0; i<data.length; i++){
					var t = NewsTemplate.List.entry.image;
					var d = data[i];
					t = t.replace("{newshash}", d.newshash);
					t = t.replace("{fulltitle}", d.title);
					t = t.replace("{subtitle}", NewsHelper.format.subTitle(d.title,20));
					t = t.replace("{intro}", NewsHelper.format.subIntro(d.intro,80));
					t = t.replace("{goodtime}", NewsHelper.format.goodTime(d.date));
					var img = ""; 
					if(d.thumb.length>0){
						var thumbs = d.thumb.split("|");
						img = '<img src="'+NewsHelper.format.imageURL(thumbs[0],"small")+'" alt="'+d.title+'" />';
					}else{
						img ='<img src="./images/nothumb.jpg" alt="暂无图片" />';	
					}
					t = t.replace("{thumb}",img);
					b.append(t);
				}
				return b.toString();
			}
		}
	  },
	  View :{
		  
		template:'<div class="view-news-head">'+
            	'<div class="view-news-head-upup">'+
                '	<span>{dig}</span>'+
                '    <a href="#">推荐</a>'+
                '</div>'+
                '<div class="view-news-head-title">'+
                '	<span>{title} <a href="{url}" target="_blank" class="news-info">查看原文</a></span>'+
                '   <div>来自：<a href="{siteUrl}" target="_blank">{siteTitle}</a> - <a href="{categoryUrl}" target="_blank">{categoryTitle}</a> {cleartime} 查看 {view} 次 </div>'+
                '</div>'+
                '<div class="view-news-head-link">'+
                '  <a href="#" title="更多" class="brief">清爽格式</a> |  <a href="" class="original">原始格式</a> |  <a href="#" class="noimg">无图格式</a> |  <a href="#" class="imgbox">图片集</a>'+
                '</div>'+
                '<div class="clear"></div>'+
            '</div>'+
            '<div class="view-news-content"> {content}</div>'+
            '<div class="view-news-url">原始地址: <a href="{url}" target="_blank">{url}</a></div>'+
            '<div class="view-news-media"></div>'+
            '<div class="view-news-nav">'+
            '	<div>上一篇：<a href="#" name="pre">{preTitle}</a></div>'+
            '   <div>下一篇：<a href="#" name="next">{nextTitle}</a></div>'+
            '</div>',
		selector:{
			digLink  :".view-news-head-upup a",
			digNum   :".view-news-head-upup span",
			nextLink :"div a[name=next]",
			preLink  :"div a[name=pre]",
			headLink : ".view-news-head-link a"
		},
		filter : {
			content : ".view-news-content",
			nav : ".view-news-nav"	
		}
	  }
  };
  
 /**
  * 新闻列表管理器
  */
  var NewsListManager = {
	//新闻列表对象列表
	//this.NewsListArray : new Array()
	///////////////////////////////////////////////////////////
	//在widget加载的时候会回调这个函数
	
	//打开查看窗口
	  
  };
  
  /**
   * 新闻查看对象
   */
   var NewsView = function(){
	   this.windowOptions = {
	   		width:960,
			title:"查看新闻",
			height:"auto",
			modal:false,
			onClose:function(){NewsView.activeView=null;}
	   };
	   //当前新闻数据
	   this.data = null;
	   //当前新闻正文jquery对象
	   this.$view = null;
	   //当前窗口
	   this.window = null;
	   //当前查看模式
	   this.bodyMode = "brief";
	   ////////////////////////////////////////////////
	   //打开指定的新闻
	   this.open = function(newshash){
		   //检查窗口是否已创建
		   if(!this.window)
		   		this.createWindow();
			//显示加载动画
			this.window.showLoadTip();
			//加载新闻
			this.load(newshash);
		
	   };
	   this.load = function(newshash){
		 //加载新闻  
		 var self = this;
		 var suc = function(data){
			 self.data = data.data;
			 self.render();
		 };
		 var err = function(){
			 self.window.setContent("加载失败，请稍后再试~");
		 };
		 var request = new ServerRequest({
				url     : Config.Path.Index+Config.URL.NewsDetail.replace("{newshash}",newshash),
				dataType : "json",
				success : suc,
				error   : err
			});
		 RequestManager.addRequest(request);
	   };
	   //推荐新闻
	   this.dig = function(){
		   var d = this.data.news;
		   var self = this;
		   if(NewsView.digedNews[d.newshash]){
				Message.info("你已经推荐了这个新闻，请不要重复的推荐。","已经推荐","error",null,2000,false);
				return;
		   }else{
				Message.info("正在推荐，请稍后...","正在推荐","load",null,0,false); 
				var suc = function(data){
					if(data.success){
						NewsView.digedNews[d.newshash] = true;
						self.$view.find(NewsTemplate.View.selector.digNum).text(parseInt(d.dig)+1);
						Message.activeMessage.setMessage("恭喜，推荐成功~","ok");
						Message.activeMessage.autoClose(2000);
					}
					else
						Message.activeMessage.setMessage("推荐失败，请稍后重试","error");
						Message.activeMessage.autoClose(2000);
				};
				var err = function(){
					Message.activeMessage.setMessage("推荐失败，请稍后重试","error");
					Message.activeMessage.autoClose(2000);
				};
				var request = new ServerRequest({
					url      : Config.URL.Dig.replace("{newshash}",d.newshash),
					dataType : "json",
					success  : suc,
					error    : err
				});
		   RequestManager.addRequest(request);   
		   }
	   };
	   //建立窗口
	   this.createWindow = function(){
			this.window = new Window(this.windowOptions);
			this.window.show();
	   };
	   //渲染输出新闻
	    this.render = function(){
		  var t = NewsTemplate.View.template;
		  var s = NewsTemplate.View.selector;
		  var d = this.data;
		  var n = d.news;
		  var self = this;
		  var fs = NewsTemplate.View.filter;
		  var f = ["newshash","url","title","view","dig","categoryTitle","categoryUrl","siteTitle","siteUrl"];
		  //替换变量
		  var r = new RegExp();
		  for(var i=0; i<f.length; i++){
			  	//var r = /'{'+f[i]+'}'/g
				r.compile('{'+f[i]+'}',"g");
				t = t.replace(r,n[f[i]]);  
		  }
		  //新闻正文,默认为简洁显示
		  t = t.replace("{content}",NewsHelper.format.clearContent(n.brief));
		  //时间
		  t = t.replace("{cleartime}",NewsHelper.format.clearTime(n.date));
		  //用jquery包装
		  var c = this.$view = $(t);
		  //绑定lightbox
		  c.filter(fs.content).find("a img").parent().lightBox();
		  //绑定推荐事件
		  c.find(s.digLink).click(function(){self.dig();});
		  //绑定最上面的显示方式连接
		  var $links = c.find(s.headLink);
		  $links.filter(".brief").click(function(){self.updateNewsBody("brief");return false;});
		  $links.filter(".original").click(function(){self.updateNewsBody("original");return false;});
		  $links.filter(".noimg").click(function(){self.updateNewsBody("noimg");return false;});
		  $links.filter(".imgbox").click(function(){
										    var links = self.$view.filter(NewsTemplate.View.filter.content)
												.find("a img:first");
											if(links.size()>0)
												links.parent().click();
											else
												Message.info("当前正文没有图片","提示","info",null,2000,false);
											return false;
										});
		  //上一篇和下一篇
		  var $pre  = c.filter(fs.nav).find(s.preLink); 
		  var $next = c.filter(fs.nav).find(s.nextLink);
		  d.pre ? $pre.text(d.pre.title).click(function(){NewsView.open(d.pre.newshash);}) : $pre.replaceWith("暂无新闻");
		  d.next ? $next.text(d.next.title).click(function(){NewsView.open(d.next.newshash);}) : $next.replaceWith("暂无新闻");
		  
		  //渲染到窗口中
		  this.window.hideLoadTip(function(){self.window.setContent(c);});
	  };
	  
	  //渲染新闻正文
	  this.renderNewsBody = function(type){
		var html = null;
		var n    = this.data.news;
		switch(type){
			case "noimg" :   html = NewsHelper.format.noImgContent(n.brief);break;
			case "original": html = NewsHelper.format.originalContent(n.original); break;
			case "brief" :	
			default:         html = NewsHelper.format.clearContent(n.brief);break;			
		}
		//用jquery包装
		var body = $(html);
		//启用新闻图片幻灯片
		if(type!="noimg")
			body.find("a img").parent().lightBox();
		
		return body;
	  };
	  
	  //更新新闻正文显示方式
	  this.updateNewsBody = function(type){
		  if(type!=this.bodyMode){
				this.bodyMode = type;
				this.$view.filter(NewsTemplate.View.filter.content)
					.html(this.renderNewsBody(type));
		  }
			
	  };
   };
   //当前的活动查看对象
   NewsView.activeView = null;
   //已经推荐的新闻，防止用户反复推荐
   NewsView.digedNews = {};
   //静态方法查看新闻
   NewsView.open = function(newshash){
	   if(NewsView.activeView==null){
			NewsView.activeView = new NewsView();   
	   }
		NewsView.activeView.open(newshash);   
   };
   
   
  /**
   * 新闻帮助工具
   * 主要定义了一些新闻格式化的函数
   */
   var NewsHelper = {
	   //打开查看新闻正文窗口
	   openView : function(newshash){
		   
		   
	   },
	   //格式化工具
	   format:{
		//截取指定长度的标题
		subTitle : function(title, len){
			return Util.Str.substr(title, 0, len);
		},
		//截取指定长度的简介
		subIntro : function(intro, len){
			return Util.Str.substr(intro, 0, len);
		},
		//返回缩略图片地址
		imageURL : function(id, size){
			var m = Config.URL.Media;
			m = m.replace("{media}",id);
			m = m.replace("{size}",size);
			return m;
 		},
		//返回附件ＵＲＬ
		mediaURL : function(id){
			var m = Config.URL.Media;
			m = m.replace("{media}",id);
			return m;
		},
		//从unix时间戳格式化为本地时间
		clearTime : function(timestamp){
			var date = new Date();
			date.setTime(parseInt(timestamp)*1000);
			var  b = new Util.Str.Builder();
			b.append(date.getMonth()+1);
			b.append("/");
			b.append(date.getDate());
			b.append(" ");
			b.append(date.getHours());
			b.append(":");
			b.append(date.getMinutes());
			return b.toString();
		},
		//格式化更友好的时间
		goodTime : function(timestamp){
			var curtime = Math.ceil(new Date().getTime()/1000);
			timestamp = parseInt(timestamp);
			var i   = curtime-timestamp; 
			//var n   = ["零","一","二","三","四","五","六","七","八","九","十"];
			var ret = "";
			if(i <60)
				ret = i+"秒钟前";
			else if(i<3600)
				ret = Math.ceil(i/60)+"分钟前";
			else if(i<3600*24)
				ret = Math.ceil(i/3600)+"小时前";
			else if(i<3600*24*2)
				ret = "昨天";
			else if(i<3600*24*3)
				ret = "前天";
			else{
				var date = new Date();
				date.setTime(timestamp*1000);
				ret = date.getMonth()+"/"+date.getDay(); 	
			}
			return ret;
		},
		//简洁的正文
		clearContent : function(c){
			var r = new RegExp();
			//替换媒体链接
			var u = Config.Path.Index+Config.URL.Media;
			u = u.replace("{size}","full");
			u = u.replace("{media}","$1");
			var p = "\\[__MEDIA__\\|(.*?)\\]";
			c = c.replace(r.compile(p,"g"),u);
			//替换掉[]为<>
			c = c.replace(/\[/g,"<",true);
			c = c.replace(/\]/g,">",true);
			//在所有的图片标签上面加一个a标记
			p = "(<img.*?src=['\"](.*?)['\"].*?>)";
			c = c.replace(r.compile(p,"g"), '<a href="$2" title="新闻图片">$1</a>');
			return c;
			
		},
		noImgContent : function(c){
			//替换掉[]为<>
			c = c.replace(/\[/g,"<",true);
			c = c.replace(/\]/g,">",true);
			c = c.replace(/<img.*?>/,"",true);
			
			return c;
		},
		originalContent : function(c){
			//替换掉[]为<>
			var r = new RegExp();
			//替换媒体链接
			var u = Config.Path.Index+Config.URL.Media;
			u = u.replace("{size}","full");
			u = u.replace("{media}","$1");
			var p = "\\[__MEDIA__\\|(.*?)\\]";
			c = c.replace(r.compile(p,"g"),u);
			//在所有的图片标签上面加一个a标记
			p = "(<img.*?src=['\"](.*?)['\"].*?>)";
			c = c.replace(r.compile(p,"g"), '<a href="$2" title="新闻图片">$1</a>');
			return c;
		}
	   }
   };
 